package com.blog.controller;

import io.minio.MinioClient;
import io.minio.ObjectWriteArgs;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
@RestController
public class MinioUploadController {
    public MinioUploadController(){
        System.out.println("MinioUploadController()");
    }

    @Autowired
    private MinioClient minioClient;

    /**
     * @RequestPart 用于描述MultipartFile类型，并可以
     * 指定客户端要传递的属性名是什么
     * @param picFile
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/minio/upload",method = RequestMethod.POST)
    public String doUpload(@RequestPart("picFile") MultipartFile picFile)
            throws Exception{//a.jpg
        //1.为文件重命名
        String originalFilename=picFile.getOriginalFilename();
        String newFileName=UUID.randomUUID()+
                originalFilename.substring(originalFilename.lastIndexOf("."));

        ObjectWriteResponse res = minioClient.putObject(PutObjectArgs.builder()
                .bucket("public")
                .object(newFileName)
                .contentType(picFile.getContentType())
                .stream(picFile.getInputStream(), picFile.getSize(), ObjectWriteArgs.MIN_MULTIPART_SIZE).build());
        // 返回可访问的图片链接
        return "http://192.168.1.128:9000/public/" + newFileName;
    }

}
